package com.sun.aviator;

import com.google.common.collect.Maps;
import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.AviatorEvaluatorInstance;
import com.googlecode.aviator.Expression;
import com.googlecode.aviator.Options;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;

import java.math.BigDecimal;
import java.math.MathContext;
import java.util.Map;

/**
 * @Author: Suncl
 * @Date: 2023/10/26 14:15
 */
public class Demo01 {

    @Test
    public void model01() {
        String expression = "(item1-(item2+item3)*2)/2";
        Expression compile = AviatorEvaluator.compile(expression);
        String result = String.valueOf(compile.execute(compile.newEnv("item1", 99, "item2", 0, "item3", 22)));
        System.out.println(result);
    }

    @Test
    public void model02() throws NoSuchMethodException, IllegalAccessException {
        String expression = "(map1.item1-(map2.item2+map2.item3)*2)";
        Expression compile = AviatorEvaluator.compile(expression);

        Map map = Maps.newHashMap();
        Map map1 = Maps.newHashMap();
        map1.put("item1", 11);
        map1.put("item2", 12);
        map1.put("item3", 13);
        Map map2 = Maps.newHashMap();
        map2.put("item1", 21);
        map2.put("item2", 22);
        map2.put("item3", 23);
        map.put("map1", map1);
        map.put("map2", map2);
        AviatorEvaluator.setOption(Options.ALWAYS_PARSE_FLOATING_POINT_NUMBER_INTO_DECIMAL, true);
        String result = String.valueOf(compile.execute(map));
        System.out.println(result);


        AviatorEvaluator.addStaticFunctions("str", StringUtils.class);
        Expression compile1 = AviatorEvaluator.compile("str.isEmpty('')");
        System.out.println(compile1.execute());
    }

    @Test
    public void model03() {

//        instance.setOption(Options.ALWAYS_PARSE_FLOATING_POINT_NUMBER_INTO_DECIMAL,Boolean.TRUE);
        //RoundingMode

        AviatorEvaluatorInstance instance = AviatorContext.getInstance();


        Expression expression = getExpression(instance, "max(1,2,3,4,5)");

        instance.setOption(Options.ALWAYS_PARSE_FLOATING_POINT_NUMBER_INTO_DECIMAL,Boolean.TRUE);
        instance.setOption(Options.MATH_CONTEXT, new MathContext(3));

        Expression expression2 = getExpression(instance, "divide(5.3,3)");
        BigDecimal execute = new BigDecimal((String) expression2.execute());
        System.out.println(expression.execute());

        System.out.println(execute);

    }

    public Expression getExpression(AviatorEvaluatorInstance instance, String expr) {
        Expression expression;
        if (instance.isExpressionCached(expr)) {
            System.out.println("表达式=" + expr + "存在缓存");
            expression = instance.getCachedExpression(expr);
        } else {
            expression = instance.compile(expr, Boolean.TRUE);
        }
        return expression;
    }

}
